<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>Programming in Lua : 8.3</title>
<link rel="stylesheet" type="text/css" href="pil.css">
</head>
<body>
<p class="warning">
<A HREF="contents.html"><IMG TITLE="Programming in Lua (first edition)" SRC="capa.jpg" ALT="" ALIGN="left"></A>This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.<BR>The third edition targets Lua 5.2 and is available at <A HREF="http://www.amazon.com/exec/obidos/ASIN/859037985X/theprogrammil3-20">Amazon</A> and other bookstores.<BR>By buying the book, you also help to <A HREF="../donations.html">support the Lua project</A>.
</p>
<table width="100%" class="nav">
<tr>
<td width="10%" align="left"><a href="8.2.html"><img border="0" src="left.png" alt="Previous"></a></td>
<td width="80%" align="center"><a href="contents.html"><font face="Helvetica,Arial,sanserif">
<font color="gray">Programming in </font><font color="blue"> Lua</font>
</font></a></td>
<td width="10%" align="right"><a href="8.4.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
<tr>
<td width="10%" align="left"></td>
<td width="80%" align="center"><a href="contents.html#P1">Part I. The Language</a>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<a href="contents.html#8">Chapter 8. Compilation, Execution, and Errors</a></td>
<td width="10%" align="right"></td></tr>
</table>
<hr/>
<p><h2>8.3 &ndash; Errors</h2>

<p><em>Errare humanum est</em>.
Therefore, we must handle errors the best way we can.
Because Lua is an extension language,
frequently embedded in an application,
it cannot simply crash or exit when an error happens.
Instead, whenever an error occurs,
Lua ends the current chunk
and returns to the application.

<p>Any unexpected condition that Lua encounters raises an error.
Errors occur when you (that is, your program) try to add
values that are not numbers,
to call values that are not functions,
to index values that are not tables, and so on.
(You can modify this behavior using <em>metatables</em>,
as we will see later.)
You can also explicitly raise an error calling
the <code>error</code> function;
its argument is the error message.
Usually, that function is the appropriate
way to handle errors in your code:
<pre>
    print "enter a number:"
    n = io.read("*number")
    if not n then error("invalid input") end
</pre>
Such combination of <code>if not ... then error end</code>
is so common that Lua has a built-in function just for that job,
called <code>assert</code>:
<pre>
    print "enter a number:"
    n = assert(io.read("*number"), "invalid input")
</pre>
The <code>assert</code> function checks whether its first argument is not false
and simply returns that argument;
if the argument is false (that is, <B>false</B> or <B>nil</B>),
<code>assert</code> raises an error.
Its second argument, the message, is optional,
so that if you do not want to say anything in the error message,
you do not have to.
Beware, however, that <code>assert</code> is a regular function.
As such, Lua always evaluates its arguments before calling the function.
Therefore, if you have something like
<pre>
    n = io.read()
    assert(tonumber(n),
           "invalid input: " .. n .. " is not a number")
</pre>
Lua will always do the concatenation,
even when <code>n</code> is a number.
It may be wiser to use an explicit test in such cases.

<p>When a function finds an unexpected situation
(an <em>exception</em>), it can assume two basic behaviors:
It can return an error code (typically <B>nil</B>)
or it can raise an error, calling the <code>error</code> function.
There are no fixed rules for choosing between those two options,
but we can provide a general guideline:
An exception that is easily avoided should raise an error;
otherwise, it should return an error code.

<p>For instance, let us consider the <code>sin</code> function.
How should it behave when called on a table?
Suppose it returns an error code.
If we need to check for errors, we would have to write something like
<pre>
    local res = math.sin(x)
    if not res then     -- error
      ...
</pre>
However, we could as easily check this exception <em>before</em> calling the
function:
<pre>
    if not tonumber(x) then     -- error: x is not a number
      ...
</pre>
Usually, however, we check neither the argument
nor the result of a call to <code>sin</code>;
if the argument is not a number,
it means probably something wrong in our program.
In such situations, to stop the computation and to issue
an error message is the simplest and
most practical way to handle the exception.

<p>On the other hand, let us consider the <code>io.open</code> function,
which opens a file.
How should it behave when called to read a file that does not exist?
In this case, there is no simple way to check for the exception
before calling the function.
In many systems,
the only way of knowing whether a file exists is to try to open it.
Therefore,
if <code>io.open</code> cannot open a file because of an external reason
(such as <code>"file does not exist"</code> or <code>"permission denied"</code>),
it returns <B>nil</B>, plus a string with the error message.
In this way, you have a chance to handle the situation in
an appropriate way,
for instance by asking the user for another file name:
<pre>
    local file, msg
    repeat
      print "enter a file name:"
      local name = io.read()
      if not name then return end   -- no input
      file, msg = io.open(name, "r")
      if not file then print(msg) end
    until file
</pre>
If you do not want to handle such situations,
but still want to play safe,
you simply use <code>assert</code> to guard the operation:
<pre>
    file = assert(io.open(name, "r"))
</pre>
This is a typical Lua idiom:
If <code>io.open</code> fails, <code>assert</code> will raise an error.
<pre>
    file = assert(io.open("no-file", "r"))
      --> stdin:1: no-file: No such file or directory
</pre>
Notice how the error message,
which is the second result from <code>io.open</code>,
goes as the second argument to <code>assert</code>.

<hr/>
<table width="100%" class="nav">
<tr valign="top">
<td width="90%" align="left">
<small>
  Copyright &copy; 2003&ndash;2004 Roberto Ierusalimschy.  All rights reserved.
</small>
</td>
<td width="10%" align="right"><a href="8.4.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
</table>


</body></html>

